import {
  LockOutlined,
  MailOutlined,
  MobileOutlined,
  UserOutlined,
} from '@ant-design/icons';
import {
  ProForm,
  ProFormCheckbox,
  ProFormText,
} from '@ant-design/pro-components';
import { Helmet, useModel } from '@umijs/max';
import { Alert, App, Button, message } from 'antd';
import { createStyles } from 'antd-style';
import React, { useState } from 'react';
import { Footer } from '@/components';
import { register } from '@/services/auth-center/authController';
import Settings from '../../../../config/defaultSettings';

const useStyles = createStyles(({ token }) => {
  return {
    container: {
      display: 'flex',
      flexDirection: 'column',
      height: '100vh',
      overflow: 'auto',
      backgroundImage:
        "url('https://mdn.alipayobjects.com/yuyan_qk0oxh/afts/img/V-_oS6r-i7wAAAAAAAAAAAAAFl94AQBr')",
      backgroundSize: '100% 100%',
    },
    formContainer: {
      display: 'flex',
      justifyContent: 'center',
      alignItems: 'center',
      flex: 1,
      padding: '32px 0',
    },
    formWrapper: {
      width: '100%',
      maxWidth: 400,
      backgroundColor: 'white',
      borderRadius: token.borderRadius,
      padding: '24px',
      boxShadow: token.boxShadow,
    },
    logo: {
      display: 'flex',
      justifyContent: 'center',
      marginBottom: '24px',
    },
    title: {
      textAlign: 'center',
      marginBottom: '24px',
    },
    link: {
      color: token.colorPrimary,
    },
  };
});

const RegisterMessage: React.FC<{
  content: string;
}> = ({ content }) => {
  return (
    <Alert
      style={{
        marginBottom: 24,
      }}
      message={content}
      type="error"
      showIcon
    />
  );
};

const Register: React.FC = () => {
  const [registerState, setRegisterState] = useState<API.Result>({});
  const { initialState } = useModel('@@initialState');
  const { styles } = useStyles();
  const app = App.useApp();

  const handleSubmit = async (values: API.AuthDTO) => {
    try {
      // 注册
      const result = await register(values);

      if (result.code === 200) {
        message.success('注册成功！请登录');
        // 注册成功后跳转到登录页面
        setTimeout(() => {
          window.location.href = '/user/login';
        }, 1500);
      } else {
        // 处理注册失败
        setRegisterState(result);
        message.error(result.message || '注册失败，请重试！');
      }
    } catch (error) {
      console.error('注册请求错误:', error);
      message.error('网络错误，请检查网络连接！');
    }
  };

  const { message: registerMessage } = registerState.data || {};

  return (
    <div className={styles.container}>
      <Helmet>
        <title>
          {'注册'}
          {Settings.title && ` - ${Settings.title}`}
        </title>
      </Helmet>
      <div className={styles.formContainer}>
        <div className={styles.formWrapper}>
          <div className={styles.logo}>
            <img alt="logo" src="/logo.svg" />
          </div>
          <h1 className={styles.title}>注册账号</h1>

          {registerMessage && <RegisterMessage content={registerMessage} />}

          <ProForm
            onFinish={handleSubmit}
            layout="vertical"
            submitter={{
              render: (_, dom) => [
                <Button
                  key="submit"
                  type="primary"
                  htmlType="submit"
                  size="large"
                  block
                >
                  注册
                </Button>,
              ],
            }}
          >
            <ProFormText
              name="username"
              fieldProps={{
                size: 'large',
                prefix: <UserOutlined />,
              }}
              placeholder={'请输入用户名'}
              rules={[
                {
                  required: true,
                  message: '用户名是必填项！',
                },
              ]}
              style={{ marginBottom: 16 }}
            />

            <ProFormText.Password
              name="password"
              fieldProps={{
                size: 'large',
                prefix: <LockOutlined />,
              }}
              placeholder={'请输入密码'}
              rules={[
                {
                  required: true,
                  message: '密码是必填项！',
                },
                {
                  min: 6,
                  message: '密码长度不能少于6位！',
                },
              ]}
              style={{ marginBottom: 16 }}
            />

            <ProFormText.Password
              name="confirmPassword"
              fieldProps={{
                size: 'large',
                prefix: <LockOutlined />,
              }}
              placeholder={'请确认密码'}
              rules={[
                {
                  required: true,
                  message: '请确认密码！',
                },
              ]}
              style={{ marginBottom: 16 }}
            />

            <ProFormText
              name="email"
              fieldProps={{
                size: 'large',
                prefix: <MailOutlined />,
              }}
              placeholder={'请输入邮箱(选填)'}
              rules={[
                {
                  type: 'email',
                  message: '请输入有效的邮箱地址！',
                },
              ]}
              style={{ marginBottom: 16 }}
            />

            <ProFormText
              name="phone"
              fieldProps={{
                size: 'large',
                prefix: <MobileOutlined />,
              }}
              placeholder={'请输入手机号(选填)'}
              rules={[
                {
                  pattern: /^1\d{10}$/,
                  message: '不合法的手机号！',
                },
              ]}
              style={{ marginBottom: 24 }}
            />

            <ProFormCheckbox noStyle name="agreement">
              我已阅读并同意 <a className={styles.link}>用户协议</a> 和{' '}
              <a className={styles.link}>隐私政策</a>
            </ProFormCheckbox>

            <div style={{ textAlign: 'center', marginTop: 16 }}>
              已有账号？{' '}
              <a href="/user/login" className={styles.link}>
                立即登录
              </a>
            </div>
          </ProForm>
        </div>
      </div>
      <Footer />
    </div>
  );
};

export default Register;
